package com.em.tuppence.web.security.details;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.em.tuppence.core.model.application.User;
import com.em.tuppence.web.services.client.UserServiceProxy;

public class TuppenceUserDetailsService implements UserDetailsService {

	private static final Logger logger = LoggerFactory.getLogger(TuppenceUserDetailsService.class);

	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//keeping in mind that username here is ACUTALLY id url, or userid from the OpenID system
		UserDetails details = null;
		
		//log
		TuppenceUserDetailsService.logger.debug("Connected to remote tuppence-user-service");
		
		UserServiceProxy proxy = new UserServiceProxy();
		Object result = proxy.getUser(username);
		//destroy proxy when done
		proxy.destroy();
		
		if(result instanceof User) {
			User foundUser = (User)result;
			details = new TuppenceUserDetails(foundUser);
			TuppenceUserDetailsService.logger.info("Found a user and populated user details.");
		} else if(result instanceof Exception) {
			//error!
			TuppenceUserDetailsService.logger.info("An exception was returned from tuppence-user-service.");
		} else {
			//non-user/non-exception object found
			TuppenceUserDetailsService.logger.info("User service returned an unexpected response, treating it as no user found.");
			throw new UsernameNotFoundException("User service returned an unexpected response, treating it as no user found.");
		}
		
		//return user details
		return details;
	}

}
